package net.sky.oa.util;
import java.util.ArrayList;
import java.util.List;

import montnets.MWGateway;

public class MsgOperate {

	private static final String SERVERIP = "211.154.151.136";
	private static final int SERVERPORT = 8018;
	private static int sock = -1;

	/**
	 * 说明: 短信发送函数
	 * 
	 * @param userId
	 *            短信帐号
	 * @param password
	 *            密码
	 * @param content
	 *            短信内容
	 * @param mobiles
	 *            手机号码,同时多个手机号时,手机号码需用逗号分开
	 * @return int 返回为1时,短信发送成功;返回小于1时,参照MWGateway接口说明书对应其错误类型
	 */
	public static int sendMsg(String userId, String password, String content,
			String mobiles) {
		userId="lt-c001";
		password="123";
		sock = MWGateway.Connect(SERVERIP, SERVERPORT, userId, password);
		if (sock < 0) {
			System.out.println("socked is invalid!");
			return sock;
		}
		String[] m = mobiles.split(",");// 获取手机个数
		String status=MWGateway.CsSendSms(sock, mobiles, content, m.length);
		System.out.println("status:"+status);
		//String status = MWGateway.CsSPSendSms(sock, mobiles, content, m.length, userId.substring(userId.length()-3));//
		//MWGateway.CsSendSms(sock, mobiles, content, m.length);此方法不支持长短信
		//System.out.println(status);
		MWGateway.Disconnect(sock);
		if ("Err".equals(status.substring(0, 3))) {
			String[] subStr = status.split(",");
			int errType = Integer.valueOf(subStr[1]);
			return errType;
		}
		return 1;
	}
	
	public static void main(String[] args) {
		sendMsg("lt-c001","123","测试信息1","15986656534");
//		List<Reply> li=getMsg("lt-c001","123");
//		for(Reply re : li){
//			System.out.println(re.getContent());
//		}
	}
	
	/**
	 * 说明: 短信接收函数
	 * @param userId
	 *            短信帐号
	 * @param password
	 *            密码
	 * @return List<Reply> 返回为null时,无回复短信;
	 */
	public static List<Reply> getMsg(String userId, String password) {
		sock = MWGateway.Connect(SERVERIP, SERVERPORT, userId, password);
		String[] arrMsg = MWGateway.CsGetSms(sock);
		List<Reply> arrList = new ArrayList<Reply>();
		for (String am : arrMsg) {
			Reply replay = new Reply();
			if ("OK,0".equals(am)) {
				return null;
			} else {
				String[] arrtemp = am.split(",");
				try {
					replay.setRecDate(arrtemp[0] + " " + arrtemp[1]);// 可能会抛出字符类型转换异常
					replay.setMobile(arrtemp[2]);
					replay.setSpNumber(arrtemp[3]);
					replay.setContent(new String(arrtemp[5].getBytes(), "GBK"));// 可能会抛出unsupportEncoding异常
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			arrList.add(replay);
		}
		return arrList;
	}

	/*
	 * 说明:短信接收函数
	 * @param userId 短信账号
	 * @param password 账号密码
	 * @return String
	 */
	public static String[] recieveMsg(String userId,String password) {
		sock = MWGateway.Connect(SERVERIP, SERVERPORT, userId, password);
		if(sock<0) {			
			return null;
		}
		String[] arrMsg = MWGateway.CsGetSms(sock);		
		return arrMsg;
	}
}
